"use client";

import { Box, Center } from "@chakra-ui/react";
import InsertMacroAction from "./InsertMacroAction";
import { CloseIcon } from "@chakra-ui/icons";
import MacroKeyAction from "./MacroKeyAction";
import MacroTimeAction from "./MacroTimeAction";
import { MacroAction } from "@/src/types/types.v1";
import MacroMouseAction from "./MacroMouseAction";
import { useSortable } from "@dnd-kit/sortable";
import { CSS } from "@dnd-kit/utilities";

function MacroActionItem({
  index,
  action,
  actions,
  hoverAction,
  setHoverAction,
  insertAction,
  removeAction,
  changeAction,
  onChange,
}: {
  index: number;
  action: MacroAction;
  actions: MacroAction[];
  hoverAction: number;
  setHoverAction: Function;
  insertAction: Function;
  removeAction: Function;
  changeAction: Function;
  onChange: Function;
}) {
  const { attributes, listeners, setNodeRef, transform, transition } =
    useSortable({ id: action.id });

  const style = {
    transform: CSS.Transform.toString(transform),
    transition,
  };

  return (
    <Box ref={setNodeRef} sx={style} {...attributes} {...listeners}>
      <Box
        className="flex items-center px-4 macro-action justify-center relative"
        onMouseEnter={() => setHoverAction(index)}
        onMouseLeave={() => setHoverAction(-1)}
      >
        {hoverAction == index && (
          <Box className="add-action absolute top-[14px] -left-[14px]">
            <InsertMacroAction onInsert={(type) => insertAction(type, index)} />
          </Box>
        )}
        <Box className="relative">
          <Center
            className="add-action absolute -right-2 -top-2 w-5 h-5 bg-red-500 rounded-full z-20 "
            onClick={() => removeAction(index)}
          >
            <CloseIcon boxSize={2} color={"white"} />
          </Center>
          {action.type == 1 && (
            <MacroKeyAction
              action={action}
              onChange={(newAction) => changeAction(newAction, index)}
            />
          )}
          {action.type == 3 && (
            <MacroMouseAction
              action={action}
              onChange={(newAction) => changeAction(newAction, index)}
            />
          )}
          {action.type == 2 && (
            <MacroTimeAction
              action={action}
              onChange={(newAction) => {
                onChange(
                  actions.map((action, idx) =>
                    idx == index ? newAction : action
                  )
                );
              }}
            />
          )}
        </Box>
        {hoverAction == index && (
          <Box className="add-action absolute top-[14px] -right-[14px]">
            <InsertMacroAction
              onInsert={(type) => insertAction(type, index + 1)}
            />
          </Box>
        )}
      </Box>
    </Box>
  );
}

export default MacroActionItem;
